package com.example.guava.future;

import com.google.common.util.concurrent.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author ZhenWuWang
 */
public class ListenableFutureDemo
{
    //successfulAsList(Iterable<ListenableFuture<V>>) 是否异步执行
    //线程池溢出辉怎么样
    //fal-in

    private ExecutorService threadPool = new ThreadPoolExecutor(5, 5, 1,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(5),
            new ThreadPoolExecutor.DiscardPolicy());

    private ListeningExecutorService service = MoreExecutors.listeningDecorator(threadPool);


    public static void main(String[] args)
    {
//        ListenableFutureDemo listenableFutureDemo = new ListenableFutureDemo();
//        try
//        {
////            listenableFutureDemo.testSubmit();
//        } catch (ExecutionException | InterruptedException e)
//        {
//            e.printStackTrace();
//        }
    }


    public void testSubmit() throws ExecutionException, InterruptedException
    {
        ListenableFuture<Integer> listenableFuture = service.submit(() ->
        {
            System.out.println("start");
            TimeUnit.SECONDS.sleep(3);
            return 0;
        });
        System.out.println("get");
        int v = listenableFuture.get();
        System.out.println("v:" + v);
        System.out.println("end");
    }

    public void testSuccessfulAsList()
    {
        List<ListenableFuture<String>> futureList = new ArrayList<>();
        for (int i = 0; i < 5; i++)
        {
//            ListenableFuture<String> future = ListenableFutureTask.create(new MyCallable("线程" + i));
            ListenableFuture<String> future = service.submit(new MyCallable("线程" + i));
            futureList.add(future);
        }


    }

    private static class MyCallable implements Callable<String>
    {
        private final String name;

        private MyCallable(String name)
        {
            this.name = name;
        }

        @Override
        public String call() throws Exception
        {
            for (int i = 0; i < 5; i++)
            {
                System.out.println(name + ": " + i);
                TimeUnit.SECONDS.sleep(1);
            }
            return name;
        }
    }

}
